package com.team.client_server;

import java.io.IOException;
import java.net.Socket;

import com.team.communication.AnalyseurDeMessageClient;
import com.team.communication.ClientRequest;

public class ConnectClient extends Connect{

	boolean init = false;
	AnalyseurDeMessageClient analyser;
	
	public ConnectClient(Socket socket) {
		super(socket);
		initConnection();
		analyser = new AnalyseurDeMessageClient(this);
	}
	public void initConnection(){
		seq = 0;
		//am = new AnalyseurDeMessageClient();
		ClientMessage m = new ClientMessage(MessageHeader.INIT_CONNECTION, 0, 0, null,null);
		send(m);
		while(!init){}
	}
	
	public void run (){

		System.out.println("-------Enable to receive message--------");
		
		while (true){
			try {
				//-----------------------------------------------------------------------------------
				int t = 0;
				String tmp="" ;
				do {
					t = socket.getInputStream().read();
					tmp = tmp + (char)t;
				}while (t!=10) ;

				//----------------------------------------------------------------------------------- 	
				System.out.println("Receive -->" + tmp ) ;
				ServerMessage m = new ServerMessage(tmp);
				
				switch (m.getMessageHeader()){
				case MESSAGE : sendAck(m);
					analyser.traiterMessage(m); 
					seq=m.getSequenceNumber();
					break;
				case ACKNOWLEDGE : 
					receiveAck(m); 
					break;
				case INIT_CONNECTION : 
					setId(m.getId());
					init = true;
					break;
//				case INFORMATION : 
//					receiveInformation(m);break;
				case ERROR : 
					break;
				default : 
					break;
				}

			}catch (IOException a ) {
				System.out.println("erreur2") ;
				a.printStackTrace() ;  }//catch IO

		}//while
	}//run
	protected void receiveAck(ServerMessage m) {
		// TODO Auto-generated method stub
		//supprime message du buffer
	}

	
	/**
	 * envoi l'acquitement d'un message
	 * @param m
	 */
	public void sendAck (ServerMessage m){
		ClientMessage tmp = new ClientMessage(MessageHeader.ACKNOWLEDGE, id, m.getSequenceNumber(), null, ClientRequest.ACK);
		//System.out.println(tmp.createMessage());	
		send(tmp);
	}//sendAck
	
	
	//send information pour un popup
//	public void sendInformation(String information){
//		seq++;
//		ClientMessage m = new ClientMessage(MessageHeader.INFORMATION, id, seq, information, new String[0]);
//		send(m);
//	}
	
	public void sendMessage(ClientRequest request,String[] arg){
		seq++;
		ClientMessage m = new ClientMessage(MessageHeader.MESSAGE,id,seq,arg, request);
		send(m);
	}
	
	

	protected void send(ClientMessage m){	
		if(m.getMessageHeader() == MessageHeader.MESSAGE){
			saveMessage(m);
		}
		System.out.println("send --> "+m.createMessage());
		out.println(m.createMessage());
		out.flush();
	}
	
	protected void saveMessage(Message m) {
		//mettre dans la HashMap
		
	}
//	protected void receiveInformation(Message m) {
//		// TODO Auto-generated method stub
//		System.out.println(m.request);
//	}

}
